package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.ControllerAuthority;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 防止重复提交拦截器
 *
 * @author ruoyi
 */
//@Component
public abstract class ControllerAuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        BaseController controller = getController(handler, BaseController.class);
        if (Objects.nonNull(controller)) {
            ControllerAuthority authority = controller.getClass()
                    .getAnnotation(ControllerAuthority.class);
            if (Objects.nonNull(authority)) {
                if (!this.isPermission(request, authority)) {
                    AjaxResult ajaxResult = AjaxResult.error(authority.message());
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 验证control是否有权限访问
     *
     * @param request HttpServletRequest
     * @return true 允许访问 ， false 不允许访问
     */
    public abstract boolean isPermission(HttpServletRequest request, ControllerAuthority authority);

    protected <T> T getController(Object handler, Class<T> clazz) {
        handler = getController(handler);
        if (handler != null && clazz != null) {
            if (clazz.isAssignableFrom(handler.getClass())) {
                return ((T) handler);
            }
        }
        return null;
    }

    private Object getController(Object handler) {
        if (handler instanceof HandlerMethod) {
            return ((HandlerMethod) handler).getBean();
        }
        return handler;
    }

}
